package com.common.web;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.common.component.Pagination;
import com.common.manager.CparamManager;
import com.common.manager.RoleInfoManager;
import com.common.manager.StaffManager;
import com.common.model.StaffInfoModel;
import com.common.utils.DateUtil;
import com.framework.model.IData;
import com.framework.model.impl.DataMap;
import com.framework.web.BaseController;

@Controller
@RequestMapping(value = "/management/staff")
public class StaffInfoController extends BaseController{

	 private static String modelUrl="/management/staff/";
	 
    @Autowired
	private StaffManager staffManager;
    
    @Autowired
	private RoleInfoManager roleInfoManager;
    
    
    @Autowired
	private CparamManager cparamManager;
    
    
    

    /**
     * 功能：页面分页列表
     * @param vo
     * @param param
     * @return
     */
	@RequestMapping("/pageList")
	public ModelAndView pageList(@ModelAttribute("page") Pagination vo,@ModelAttribute("staffInfoModel") StaffInfoModel param) {
		ModelAndView modelView = new ModelAndView(modelUrl+"list");
		List<DataMap> dataList = staffManager.getPageObjectList(vo, param);
		modelView.addObject("vo", vo);
		modelView.addObject("param", param);
		modelView.addObject("objList", dataList);
		return modelView;
	}
	
	
	/**
	 * 功能：初始化添加页面
	 * @param staffInfoModel
	 * @return
	 */
	@RequestMapping("initAdd")
	public ModelAndView initAdd(@ModelAttribute("staffInfoModel") StaffInfoModel staffInfoModel) {
		ModelAndView modelView = new ModelAndView(modelUrl+"add");
		log.info("add is page");
		initRoleList(modelView);
		cparamManager.getCparamList(modelView, "'SYS_BASEPAY','SYS_POSITION','SYS_SYSSTATUS','SYS_PSEX'");
		staffInfoModel.setEntryDate(DateUtil.getCurrentDate());
		staffInfoModel.setFullDate(DateUtil.getMonth(3));
		modelView.addObject("vo",staffInfoModel);
		return modelView;
	}
	
	/**
	 * 功能：初始化编辑页面
	 * @param intID
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/{intID}/initEdit")
	public ModelAndView initEdit(@PathVariable("intID") String intID) {
		ModelAndView modelView = new ModelAndView(modelUrl+"update");
		IData dataMap = new DataMap();
		dataMap.put("intID", intID);
		StaffInfoModel staffInfoModel = (StaffInfoModel)staffManager.getObjectInfo(dataMap);
		initRoleList(modelView);
		cparamManager.getCparamList(modelView, "'SYS_BASEPAY','SYS_POSITION','SYS_SYSSTATUS','SYS_PSEX'");
		modelView.addObject("vo",staffInfoModel);
		return modelView;
	}
	
	private void initRoleList(ModelAndView modelView){
		List roleList = roleInfoManager.getObjectList(new DataMap());
		modelView.addObject("roleList",roleList);
	}
	
	/**
	 * 功能：执行插入操作
	 * @param staffInfoModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping("add")
	public Object insert(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("staffInfoModel") StaffInfoModel staffInfoModel) {
		try{
			int opNum = staffManager.insertStaff(staffInfoModel);
			if(opNum>0){
				return super.jsonReturn(response,200);
			}else{
				return super.jsonReturn(response,300);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return super.jsonReturn(response,300,e.getMessage());
		}
	}
	
	/**
	 * 功能：执行更新操作
	 * @param staffInfoModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping("update")
	public Object update(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("staffInfoModel") StaffInfoModel staffInfoModel) {
		try{
			String newPwd = request.getParameter("loginPwd1");
			int opNum =staffManager.updateStaff(newPwd,staffInfoModel);
			if(opNum>0){
				return super.jsonReturn(response,200,true);
			}else{
				return super.jsonReturn(response,300,true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return super.jsonReturn(response,300,e.getMessage(),true);
		}
	}
	
	/**
	 * 功能：执行单记录删除
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/{intID}/delete")
	public Object delete(HttpServletResponse response,@PathVariable("intID") int intID) {
		try{
			IData dataMap = new DataMap();
			dataMap.put("intID", intID);
			int opNum =staffManager.deleteObject(dataMap);
			if(opNum>0){
				return super.jsonReturn(response,200,false);
			}else{
				return super.jsonReturn(response,300,false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return super.jsonReturn(response,300,e.getMessage(),false);
		}
	}
	
	/**
	 * 功能：执行批量删除
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deleteAll")
	public Object deleteAll(HttpServletResponse response,HttpServletRequest request) {
		String ids = request.getParameter("ids");
		try{
			IData dataMap = new DataMap();
			dataMap.put("ids", ids);
			int opNum =staffManager.deleteObject("deleteAllObject",dataMap);
			if(opNum>0){
				return super.jsonReturn(response,200,false);
			}else{
				return super.jsonReturn(response,300,false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return super.jsonReturn(response,300,e.getMessage(),false);
		}
	}
	
	/**
	 * 功能：检查机构编码是否正常
	 * @param response
	 * @param request
	 */
	@ResponseBody
	@RequestMapping("/checkStaffNum")
	public void checkStaffNum(HttpServletResponse response,HttpServletRequest request){
		String staffNum = request.getParameter("staffNum");
		boolean isFlag= true;
		JSONObject rtnMsg = new JSONObject();
		if(staffNum!=null){
				try {
					isFlag =  staffManager.checkStaffNum(staffNum);
					if(!isFlag){
						rtnMsg.put("msg", "员工工号已存在请重新输入");
					}else{
						rtnMsg.put("msg", "校验通过");
					}
				} catch (Exception e) {
					isFlag =false;
					rtnMsg.put("msg", "校验发生异常");
				}
		}else{
			rtnMsg.put("msg", "员工工号不能为空");
		}
		rtnMsg.put("isFlag", isFlag);
		this.ajaxJson(response, rtnMsg.toString());
	}
	
	/**
	 * 功能：上传用户照片
	 * @param response
	 * @param request
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadUserPic")
	public Object uploadUserPic(
	        @RequestParam(value = "file") MultipartFile file,
	        HttpServletRequest request, HttpServletResponse response) {
		JSONObject rtnMsg = new JSONObject();
	    if (file != null) {
	        //获取保存的路径，
	        String realPath = request.getSession().getServletContext()
	                .getRealPath("/upload");
	        if (file.isEmpty()) {
	        	rtnMsg.put("statusCode", "300");
	            rtnMsg.put("msg", "未选择文件");
	        } else{
	            // 文件原名称
	            String originFileName = file.getOriginalFilename();
	            try {
	                //这里使用Apache的FileUtils方法来进行保存
	            	String saveName = new Date().getTime()+"_" + originFileName;
	                FileUtils.copyInputStreamToFile(file.getInputStream(),
	                        new File(realPath, saveName));
	                
	                String picUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/upload/"+saveName;
	                rtnMsg.put("statusCode","200");
	                rtnMsg.put("filename", picUrl);
	                rtnMsg.put("msg", "文件上传成功");
	            } catch (IOException e) {
	                System.out.println("文件上传失败");
	                rtnMsg.put("statusCode", "300");
	                rtnMsg.put("msg", "文件上传失败");
	                e.printStackTrace();
	            }
	        }
	 
	    }
	    return ajaxJson(response, rtnMsg.toString());
	}

}